<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="vjImUBDCK8Rg9G13vkIip_GUsZTtVV6s-XdSk81-jzA" />













  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Kotlin,Collection," />





  <link rel="alternate" href="/atom.xml" title="旺仔的个人博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.png?v=5.1.2" />






<meta name="description" content="集合(Collections)Kotlin的集合类型和Java不一样，Kotlin的集合分为可变（读写）和不可变（只读）类型（lists, sets, maps, etc），可变类型是在不可变类型前面加Mutable：  List&amp;lt;out E&amp;gt;和MutableList&amp;lt;E&amp;gt; Set&amp;lt;out E&amp;gt;和MutableSet&amp;lt;E&amp;gt; Map&amp;lt;K, ou">
<meta name="keywords" content="Kotlin,Collection">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin学习_集合（Collections）和范围（Ranges）">
<meta property="og:url" content="http://www.jowanxu.top/2017/06/19/Kotlin学习_集合和范围/index.html">
<meta property="og:site_name" content="旺仔的个人博客">
<meta property="og:description" content="集合(Collections)Kotlin的集合类型和Java不一样，Kotlin的集合分为可变（读写）和不可变（只读）类型（lists, sets, maps, etc），可变类型是在不可变类型前面加Mutable：  List&amp;lt;out E&amp;gt;和MutableList&amp;lt;E&amp;gt; Set&amp;lt;out E&amp;gt;和MutableSet&amp;lt;E&amp;gt; Map&amp;lt;K, ou">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-040c15bca5c90313.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-9ae79ad798e915b3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-1f953751f462ca0e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-4eb3928bbd8ccdda.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-c6206d12aff50b18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-666243775217aa0d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-408f825475db293d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-350f615d7e5cf4c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-b7c51aae44f94512.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-d6d32c6b39ce9e38.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-7e0e8afd04be6d14.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-0a5122c1550c5e60.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-cdf93171a6e99e9c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-4dbbcd183f81d544.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-c6206d12aff50b18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-5d404281307dc936.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-da1aa664ce35889b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-d5dfed540ce0a4c3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-22396eae92393dc9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-c6206d12aff50b18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-47c9f2246d039cfc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-6d65d5caa33ebc09.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-30e56446ead478ef.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-294e5817feffe3ef.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-29T00:20:08.998Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Kotlin学习_集合（Collections）和范围（Ranges）">
<meta name="twitter:description" content="集合(Collections)Kotlin的集合类型和Java不一样，Kotlin的集合分为可变（读写）和不可变（只读）类型（lists, sets, maps, etc），可变类型是在不可变类型前面加Mutable：  List&amp;lt;out E&amp;gt;和MutableList&amp;lt;E&amp;gt; Set&amp;lt;out E&amp;gt;和MutableSet&amp;lt;E&amp;gt; Map&amp;lt;K, ou">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/1241355-040c15bca5c90313.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.jowanxu.top/2017/06/19/Kotlin学习_集合和范围/"/>





  <title>Kotlin学习_集合（Collections）和范围（Ranges） | 旺仔的个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>
    <a href="https://github.com/wangzailfm"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">旺仔的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">叫我旺仔<br/>Android Developer</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.jowanxu.top/2017/06/19/Kotlin学习_集合和范围/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jowan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="旺仔的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Kotlin学习_集合（Collections）和范围（Ranges）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-19T09:31:59+08:00">
                2017-06-19
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2017-11-29T08:20:08+08:00">
                2017-11-29
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Kotlin/" itemprop="url" rel="index">
                    <span itemprop="name">Kotlin</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"> 文章热度</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>°C
            </span>
          

          
            <br/>
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">文章字数</span>
                
                <span title="文章字数">
                  1,335 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长需</span>
                
                <span title="阅读时长需">
                  6 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://upload-images.jianshu.io/upload_images/1241355-040c15bca5c90313.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Kotlin"></p>
<h2 id="集合-Collections"><a href="#集合-Collections" class="headerlink" title="集合(Collections)"></a>集合(Collections)</h2><p>Kotlin的集合类型和Java不一样，Kotlin的集合分为可变（读写）和不可变（只读）类型（lists, sets, maps, etc），可变类型是在不可变类型前面加<code>Mutable</code>：</p>
<ul>
<li><code>List&lt;out E&gt;</code>和<code>MutableList&lt;E&gt;</code></li>
<li><code>Set&lt;out E&gt;</code>和<code>MutableSet&lt;E&gt;</code></li>
<li><code>Map&lt;K, out V&gt;</code>和<code>MutableMap&lt;K, V&gt;</code></li>
</ul>
<a id="more"></a>
<p>举个栗子：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">val</span> numbers: MutableList&lt;<span class="built_in">Int</span>&gt; = mutableListOf(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</div><div class="line"><span class="keyword">val</span> readOnlyView: List&lt;<span class="built_in">Int</span>&gt; = numbers</div><div class="line">println(numbers)        <span class="comment">// prints "[1, 2, 3]"</span></div><div class="line">numbers.add(<span class="number">4</span>)</div><div class="line">println(readOnlyView)   <span class="comment">// prints "[1, 2, 3, 4]"</span></div><div class="line"><span class="comment">// readOnlyView.clear()    // 报错</span></div><div class="line"></div><div class="line"><span class="keyword">val</span> strings = hashSetOf(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"c"</span>)</div><div class="line">assert(strings.size == <span class="number">3</span>)</div></pre></td></tr></table></figure></p>
<p>为什么加了<code>Mutable</code>前缀就是可变类型？</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-9ae79ad798e915b3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Collections"></p>
<p>我们先来看List，List实现了Collection接口，而MutableList实现的是List和MutableCollection接口</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-1f953751f462ca0e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Collection"></p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-4eb3928bbd8ccdda.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="MutableCollection"></p>
<p>可以看出，MutableCollection接口实现了Collection接口，并且在里面添加了<code>add</code>和<code>remove</code>等操作方法，<br>所以加了<code>Mutable</code>前缀就是可变类型，而没有的就是不可变类型。</p>
<h3 id="创建集合"><a href="#创建集合" class="headerlink" title="创建集合"></a>创建集合</h3><p>Kotlin没有用于创建列表或集合的专用语法结构，只能使用标准库中的方法：<code>listOf()</code>, <code>mutableListOf()</code>, <code>setOf()</code>, <code>mutableSetOf()</code>,<code>mapOf()</code>等等。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 等同于Java的List&lt;String&gt; list = new ArrayList();</span></div><div class="line"><span class="keyword">val</span> list: List&lt;String&gt; = arrayListOf()</div><div class="line"><span class="keyword">val</span> mutableList: MutableList&lt;String&gt; = mutableListOf()</div><div class="line"><span class="comment">// 也可以这样写</span></div><div class="line"><span class="keyword">val</span> list2 = mutableListOf&lt;String&gt;()</div><div class="line"><span class="keyword">val</span> mutableList2 = mutableListOf&lt;String&gt;()</div><div class="line"></div><div class="line"><span class="comment">// 等同于Java的Map&lt;String, String&gt; map = new HashMap();</span></div><div class="line"><span class="keyword">val</span> map: Map&lt;String, String&gt; = mapOf()</div><div class="line"><span class="keyword">val</span> mutableMap: MutableMap&lt;String, String&gt; = mutableMapOf()</div><div class="line"><span class="comment">// 也可以这样写</span></div><div class="line"><span class="keyword">val</span> map2 = mapOf&lt;String, String&gt;()</div><div class="line"><span class="keyword">val</span> mutableMap2 = mutableMapOf&lt;String, String&gt;()</div></pre></td></tr></table></figure>
<p>其中<code>mapOf()</code>可以简写成<code>mapOf(a to b, c to d)</code><br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">val</span> map: Map&lt;<span class="built_in">Int</span>, <span class="built_in">Int</span>&gt; = mapOf(<span class="number">1</span> to <span class="number">1</span>, <span class="number">2</span> to <span class="number">2</span>)</div></pre></td></tr></table></figure></p>
<h2 id="范围-Ranges"><a href="#范围-Ranges" class="headerlink" title="范围(Ranges)"></a>范围(Ranges)</h2><p>范围表达式由<code>rangeTo</code>函数形成，操作符形式为<code>..</code>，由<code>in</code>和<code>!in</code>进行连接，可以用于判断，也可用于循环当中：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (i <span class="keyword">in</span> <span class="number">1.</span><span class="number">.10</span>) &#123; <span class="comment">// i in 1..10 等同于1 &lt;= i &amp;&amp; i &lt;= 10</span></div><div class="line">    println(i) </div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>为什么<code>..</code>能够替换<code>rangeTo</code>函数，这就涉及到运算符的重载了。</p>
<h3 id="运算符重载"><a href="#运算符重载" class="headerlink" title="运算符重载"></a>运算符重载</h3><p><img src="http://upload-images.jianshu.io/upload_images/1241355-c6206d12aff50b18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="rangeTo"></p>
<p>Kotlin提供了一些运算符，这些运算符有固定的符号表示形式（如<code>+</code>或<code>-</code>），运算符重载要在函数加<code>operator</code>关键字，在使用直接用运算符来替换函数，如<code>..</code>替换<code>rangeTo</code>函数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (i <span class="keyword">in</span> <span class="number">1.</span><span class="number">.10</span>) &#123; </div><div class="line">    println(i) </div><div class="line">&#125;</div><div class="line"><span class="comment">// 等同与</span></div><div class="line"><span class="keyword">if</span> (i <span class="keyword">in</span> <span class="number">1.</span>rangeTo(<span class="number">10</span>)) &#123;</div><div class="line">    println(i) </div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h4 id="常见运算符"><a href="#常见运算符" class="headerlink" title="常见运算符"></a>常见运算符</h4><p>如<code>+</code>、<code>%</code>、<code>in</code>、<code>==</code>等等，都是运算符重载。</p>
<h5 id="前缀运算符"><a href="#前缀运算符" class="headerlink" title="前缀运算符"></a>前缀运算符</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-666243775217aa0d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<h5 id="递增和递减"><a href="#递增和递减" class="headerlink" title="递增和递减"></a>递增和递减</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-408f825475db293d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<h5 id="算术运算符"><a href="#算术运算符" class="headerlink" title="算术运算符"></a>算术运算符</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-350f615d7e5cf4c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<h5 id="in和-in运算符"><a href="#in和-in运算符" class="headerlink" title="in和!in运算符"></a><code>in</code>和<code>!in</code>运算符</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-b7c51aae44f94512.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<h5 id="索引访问操作符"><a href="#索引访问操作符" class="headerlink" title="索引访问操作符"></a>索引访问操作符</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-d6d32c6b39ce9e38.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<h5 id="调用运算符"><a href="#调用运算符" class="headerlink" title="调用运算符"></a>调用运算符</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-7e0e8afd04be6d14.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<h5 id="赋值-Augmented-assignments"><a href="#赋值-Augmented-assignments" class="headerlink" title="赋值(Augmented assignments)"></a>赋值(Augmented assignments)</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-0a5122c1550c5e60.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p><strong>注意：赋值在 Kotlin 中不是表达式。</strong></p>
<h5 id="等式运算符"><a href="#等式运算符" class="headerlink" title="等式运算符"></a>等式运算符</h5><p><img src="http://upload-images.jianshu.io/upload_images/1241355-cdf93171a6e99e9c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p><strong>注意：<code>===</code>和<code>!==</code>没有被重载</strong></p>
<h5 id="比较运算符"><a href="#比较运算符" class="headerlink" title="比较运算符"></a>比较运算符</h5><p>针对<code>Int</code>类型，是去调用<code>compareTo</code>函数来比较</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-4dbbcd183f81d544.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<h2 id="范围-Ranges-1"><a href="#范围-Ranges-1" class="headerlink" title="范围(Ranges)"></a>范围(Ranges)</h2><p>范围表达式由<code>rangeTo</code>函数形成，操作符形式为<code>..</code>，由<code>in</code>和<code>!in</code>进行连接，可以用于判断，也可用于循环当中：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (i <span class="keyword">in</span> <span class="number">1.</span><span class="number">.10</span>) &#123; <span class="comment">// i in 1..10 等同于1 &lt;= i &amp;&amp; i &lt;= 10</span></div><div class="line">    println(i) </div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>简写<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">(<span class="number">1.</span><span class="number">.10</span>).forEach &#123; print(it) &#125;</div></pre></td></tr></table></figure></p>
<p>为什么<code>..</code>能够替换<code>rangeTo</code>函数，这就涉及到运算符的重载了。</p>
<h3 id="运算符重载-1"><a href="#运算符重载-1" class="headerlink" title="运算符重载"></a>运算符重载</h3><p><img src="http://upload-images.jianshu.io/upload_images/1241355-c6206d12aff50b18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="rangeTo"></p>
<p>运算符重载要在函数加<code>operator</code>关键字，</p>
<h3 id="Ranges是如何运行的"><a href="#Ranges是如何运行的" class="headerlink" title="Ranges是如何运行的"></a>Ranges是如何运行的</h3><p>Ranges包含三种<code>IntRange</code>，<code>LongRange</code>，<code>CharRange</code>，都是实现了通用接口<code>ClosedRange&lt;T&gt;</code></p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-5d404281307dc936.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="ClosedRange"></p>
<p><code>ClosedRange&lt;T&gt;</code>表示在数学意义上的闭区间，定义为可比较类型，具有两个端点<code>start</code>和<code>endInclusive</code>，以及包含的范围，用<code>in</code>和<code>!in</code>来进行操作。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-da1aa664ce35889b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Progression"></p>
<p>Ranges在实现<code>ClosedRange&lt;T&gt;</code>的同时，也分别继承了相对应的运算进度类，如<code>IntRange</code>继承了<code>IntProgression</code>类，由<code>first</code>元素，<code>last</code>元素和不为零的<code>step</code>来定义，第一个元素是<code>first</code>元素，后面的元素是上一个元素加上<code>step</code>的结果。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-d5dfed540ce0a4c3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Iterable"></p>
<p><code>Progression</code>进度类是<code>Iterable&lt;T&gt;</code>的子类，<code>T</code>包括<code>Int</code>、<code>Long</code> 和 <code>Char</code>三种类型，这就是Ranges可以用于<code>for</code>循环和<code>map</code>/<code>filter</code>等函数。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-22396eae92393dc9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="fromClosedRange"></p>
<p>在<code>Progression</code>进度类中，有个伴生对象里面的函数<code>fromClosedRange</code>用来构建进度。</p>
<p>总结下，<code>..</code>操作符创建一个实现了<code>ClosedRange &lt;T&gt;</code>和继承了<code>*Progression</code>的对象。例如<code>IntRange</code>实现了<code>ClosedRange &lt;Int&gt;</code>接口，并继承了<code>IntProgression</code>类，因此为<code>IntProgression</code>里面的所有操作都可用在<code>IntRange</code>。</p>
<h3 id="常用函数"><a href="#常用函数" class="headerlink" title="常用函数"></a>常用函数</h3><p>Ranges的函数基本都是扩展函数。</p>
<h4 id="rangeTo"><a href="#rangeTo" class="headerlink" title="rangeTo()"></a>rangeTo()</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-c6206d12aff50b18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="rangeTo"></p>
<p>默认的<code>rangeTo</code>是正序的，如果将<code>1..10</code>改为<code>10..1</code>的话，上面的循环是不会执行的：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span> (i <span class="keyword">in</span> <span class="number">10.</span><span class="number">.1</span>) &#123;</div><div class="line">     println(i) <span class="comment">// prints nothing</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>浮点数（<code>Float</code>和<code>Double</code>）不能使用<code>rangeTo</code>操作，而是使用提供的通用<code>Comparable</code>类型的标准库：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">operator</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T: Comparable&lt;T&gt;</span>&gt; T.<span class="title">rangeTo</span><span class="params">(that: <span class="type">T</span>)</span></span>: ClosedRange&lt;T&gt;</div></pre></td></tr></table></figure></p>
<p><strong>该方法不能用于循环迭代(<code>for</code>循环等等)。</strong></p>
<h4 id="downTo"><a href="#downTo" class="headerlink" title="downTo()"></a>downTo()</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-47c9f2246d039cfc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="downTo"></p>
<p><code>downTo()</code>在是扩展函数的同时，也是中缀函数，使用<code>downTo()</code>函数控制倒序输出：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span> (i <span class="keyword">in</span> <span class="number">10</span> downTo <span class="number">1</span>) &#123;</div><div class="line">     println(i) <span class="comment">// 打印10987654321</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>简写<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">(<span class="number">10</span> downTo <span class="number">1</span>).forEach &#123; print(it) &#125; <span class="comment">// 打印10987654321</span></div></pre></td></tr></table></figure></p>
<h4 id="step"><a href="#step" class="headerlink" title="step()"></a>step()</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-6d65d5caa33ebc09.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="step"></p>
<p><code>step()</code>也是中缀函数，默认间隔长度是1，如果要自定义间隔长度的话，就要使用<code>step()</code>函数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span> (i <span class="keyword">in</span> <span class="number">1.</span><span class="number">.4</span> step <span class="number">2</span>) print(i) <span class="comment">// 打印"13"</span></div><div class="line"></div><div class="line"><span class="keyword">for</span> (i <span class="keyword">in</span> <span class="number">4</span> downTo <span class="number">1</span> step <span class="number">2</span>) print(i) <span class="comment">// 打印"42"</span></div></pre></td></tr></table></figure></p>
<p>简写<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">(<span class="number">1.</span><span class="number">.4</span> step <span class="number">2</span>).forEach &#123; print(it) &#125; <span class="comment">// 打印"13"</span></div><div class="line">(<span class="number">4</span> downTo <span class="number">1</span> step <span class="number">2</span>).forEach &#123; print(it) &#125; <span class="comment">// 打印"42"</span></div></pre></td></tr></table></figure></p>
<h4 id="until"><a href="#until" class="headerlink" title="until()"></a>until()</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-30e56446ead478ef.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="until"></p>
<p><code>until()</code>也是中缀函数，要创建不包含其终端元素的范围，可以使用<code>until()</code>函数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span> (i <span class="keyword">in</span> <span class="number">1</span> until <span class="number">10</span>) &#123; <span class="comment">// i in [1, 10), 打印123456789</span></div><div class="line">     println(i)</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>简写<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">(<span class="number">1</span> until <span class="number">10</span>).forEach &#123; print(it) &#125; <span class="comment">// 打印123456789</span></div></pre></td></tr></table></figure></p>
<h4 id="reversed"><a href="#reversed" class="headerlink" title="reversed()"></a>reversed()</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-294e5817feffe3ef.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="reversed"></p>
<p><code>reversed()</code>函数，功能同单词，反向，由于<code>reversed()</code>并不是中缀函数，所以写法跟上面的那些不一样：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span> (i <span class="keyword">in</span> (<span class="number">1.</span><span class="number">.4</span>).reversed())</div><div class="line">     print(i) <span class="comment">// print 4321</span></div></pre></td></tr></table></figure></p>
<p>简写<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">(<span class="number">1.</span><span class="number">.4</span>).reversed().forEach &#123; print(it) &#125; <span class="comment">// print 4321</span></div></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Jowan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://www.jowanxu.top/2017/06/19/Kotlin学习_集合和范围/" title="Kotlin学习_集合（Collections）和范围（Ranges）">http://www.jowanxu.top/2017/06/19/Kotlin学习_集合和范围/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Kotlin/" rel="tag"><i class="fa fa-tag"></i> Kotlin</a>
          
            <a href="/tags/Collection/" rel="tag"><i class="fa fa-tag"></i> Collection</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/13/Kotlin学习_函数、高级函数和Lambda表达式/" rel="next" title="Kotlin学习_函数、高级函数和Lambda表达式">
                <i class="fa fa-chevron-left"></i> Kotlin学习_函数、高级函数和Lambda表达式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/06/28/Kotlin学习_类型别名和注解/" rel="prev" title="Kotlin学习_类型别名（Type aliases）和注解（Annotations）">
                Kotlin学习_类型别名（Type aliases）和注解（Annotations） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjA1My84NjE3"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Jowan" />
          <p class="site-author-name" itemprop="name">Jowan</p>
           
              <p class="site-description motion-element" itemprop="description">叫我旺仔<br/>Android Developer</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">27</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://plus.google.com/u/0/111824269044709365866" target="_blank" title="Google">
                  
                    
                      Google
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/wangzailfm" target="_blank" title="GitHub">
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/809077554" target="_blank" title="微博">
                  
                    
                      微博
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="673173629@qq.com" target="_blank" title="E-Mail">
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/u011976726" target="_blank" title="CSDN">
                  
                    
                      CSDN
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/u/5509a21c1623" target="_blank" title="简书">
                  
                    
                      简书
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-block">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wanandroid.com/" title="WanAndroid" target="_blank">WanAndroid</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#集合-Collections"><span class="nav-number">1.</span> <span class="nav-text">集合(Collections)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建集合"><span class="nav-number">1.1.</span> <span class="nav-text">创建集合</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#范围-Ranges"><span class="nav-number">2.</span> <span class="nav-text">范围(Ranges)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#运算符重载"><span class="nav-number">2.1.</span> <span class="nav-text">运算符重载</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#常见运算符"><span class="nav-number">2.1.1.</span> <span class="nav-text">常见运算符</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#前缀运算符"><span class="nav-number">2.1.1.1.</span> <span class="nav-text">前缀运算符</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#递增和递减"><span class="nav-number">2.1.1.2.</span> <span class="nav-text">递增和递减</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#算术运算符"><span class="nav-number">2.1.1.3.</span> <span class="nav-text">算术运算符</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#in和-in运算符"><span class="nav-number">2.1.1.4.</span> <span class="nav-text">in和!in运算符</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#索引访问操作符"><span class="nav-number">2.1.1.5.</span> <span class="nav-text">索引访问操作符</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#调用运算符"><span class="nav-number">2.1.1.6.</span> <span class="nav-text">调用运算符</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#赋值-Augmented-assignments"><span class="nav-number">2.1.1.7.</span> <span class="nav-text">赋值(Augmented assignments)</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#等式运算符"><span class="nav-number">2.1.1.8.</span> <span class="nav-text">等式运算符</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#比较运算符"><span class="nav-number">2.1.1.9.</span> <span class="nav-text">比较运算符</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#范围-Ranges-1"><span class="nav-number">3.</span> <span class="nav-text">范围(Ranges)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#运算符重载-1"><span class="nav-number">3.1.</span> <span class="nav-text">运算符重载</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Ranges是如何运行的"><span class="nav-number">3.2.</span> <span class="nav-text">Ranges是如何运行的</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用函数"><span class="nav-number">3.3.</span> <span class="nav-text">常用函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#rangeTo"><span class="nav-number">3.3.1.</span> <span class="nav-text">rangeTo()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#downTo"><span class="nav-number">3.3.2.</span> <span class="nav-text">downTo()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#step"><span class="nav-number">3.3.3.</span> <span class="nav-text">step()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#until"><span class="nav-number">3.3.4.</span> <span class="nav-text">until()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#reversed"><span class="nav-number">3.3.5.</span> <span class="nav-text">reversed()</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jowan</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
